import axios from "axios";
import store from "@/store";

// 当前封装得请求缺点：1、不能再请求未返回取消请求使用有点复杂
const XHR = {};
XHR.install = function(Vue, options) {
  Vue.post = Vue.prototype.$post = function(
    url,
    params = {},
    { log = "", convert = true, config = {} } = {}
  ) {
    let userType = store.getters.userType;
    if (userType === 3) {
      params = Object.assign(params, {
        cityId: store.getters.cityId
      });
    } else if (userType === 4) {
      params = Object.assign(params, {
        areaId: store.getters.areaId
      });
    }
    return new Promise((resolve, reject) => {
      axios(
        Object.assign(
          {
            method: "post",
            url: url,
            data: convert ? Vue.paramsConvert(params) : params
          },
          config
        )
      )
        .then(res => {
          if (res.data.code === "200") {
            // 返回结果
            resolve(res);
          } else {
            log ? console.log(`${log}-codeError`, res) : "";
            Vue.codeError(res);
            reject("code", res);
          }
        })
        .catch(error => {
          log ? console.log(`${log}-catchError`, error) : "";
          Vue.catchError(error);
          reject("catch", error);
        });
    });
  };

  Vue.get = Vue.prototype.$get = function(
    url,
    params = {},
    { log = "", config = {} } = {}
  ) {
    let userType = store.getters && store.getters.userType;

    if (userType === 3) {
      params = Object.assign(params, {
        cityId: store.getters.cityId
      });
    } else if (userType === 4) {
      params = Object.assign(params, {
        areaId: store.getters.areaId
      });
    }
    return new Promise((resolve, reject) => {
      axios(
        Object.assign(
          {
            method: "get",
            url: Vue.paramsConnect(url, params)
          },
          config
        )
      )
        .then(res => {
          if (res.data.code === "200") {
            // 返回结果
            resolve(res);
          } else {
            log ? console.log(`${log}-codeError`, res) : "";
            Vue.codeError(res);
            reject("code", res);
          }
        })
        .catch(error => {
          log ? console.log(`${log}-catchError`, error) : "";
          Vue.catchError(error);
          reject("catch", error);
        });
    });
  };
};

export default XHR;
